<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="small">
          查询搜索
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="表名：">
            <el-select v-model="listQuery.tableName" style="width:100%" clearable>
              <el-option
                  v-for="item in allTableNameToDescOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板类型：">
            <el-select v-model="listQuery.type" style="width:100%">
              <el-option label="导入模板" value="0"></el-option>
              <el-option label="导出模板" value="1"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button type="warning" size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加
      </el-button>
    </el-card>

    <div class="table-container">
      <el-table :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="表名" align="center" prop="tableName" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ allTableNameToDesc[scope.row.tableName] + "-" + scope.row.tableName }}
          </template>
        </el-table-column>
        <el-table-column label="模板类型" align="center" prop="type" width="100">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.type == '0'">导入模板</el-tag>
            <el-tag type="primary" v-if="scope.row.type == '1'">导出模板</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" align="center" prop="remark" show-overflow-tooltip/>
        <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip/>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip/>

        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleFieldMap(scope.row)">字段映射
            </el-button>
            <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.current"
          :page-size="listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑数据导入导出管理"
               :visible.sync="editDialogVisible"
               width="80%">
      <el-form :model="batchImportExportConfig"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="表名：">
          <el-select v-model="batchImportExportConfig.tableName" style="width:100%">
            <el-option
                v-for="item in allTableNameToDescOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息：">
          <el-input v-model="batchImportExportConfig.remark"></el-input>
        </el-form-item>
        <el-form-item label="模板类型：">
          <el-select v-model="batchImportExportConfig.type" style="width:100%">
            <el-option label="导入模板" value="0"></el-option>
            <el-option label="导出模板" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleEditDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增数据导入导出管理"
               :visible.sync="addDialogVisible"
               width="80%">
      <el-form :model="batchImportExportConfig"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="表名：">
          <el-select v-model="batchImportExportConfig.tableName" style="width:100%">
            <el-option
                v-for="item in allTableNameToDescOption"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息：">
          <el-input v-model="batchImportExportConfig.remark"></el-input>
        </el-form-item>
        <el-form-item label="模板类型：">
          <el-select v-model="batchImportExportConfig.type" style="width:100%">
            <el-option label="导入模板" value="0"></el-option>
            <el-option label="导出模板" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleAddDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="请选择模板"
               :visible.sync="selectTemplateDialogVisible"
               width="80%">
      <div class="table-container">
        <el-table :data="selectTemplateList"
                  style="width: 100%;"
                  v-loading="selectTemplateListLoading" border>
          <el-table-column label="表名" align="center" prop="tableName" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ allTableNameToDesc[scope.row.tableName] + "-" + scope.row.tableName }}
            </template>
          </el-table-column>
          <el-table-column label="备注信息" align="center" prop="remark" show-overflow-tooltip/>
          <el-table-column label="创建时间" align="center" prop="createTime"/>
          <el-table-column label="更新时间" align="center" prop="updateTime"/>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-upload
                  v-if="selectTemplateListQuery.type == '0'"
                  class="upload-demo"
                  action=""
                  :accept="'.xls, .xlsx'"
                  :limit="1"
                  :before-upload="beforeFileUpload"
                  :http-request="function(file){return handleSelectTemplateUpload(file,scope.row.id);}">
                <el-button size="small" type="primary">点击导入</el-button>
              </el-upload>
              <el-button size="mini" type="primary" @click="handleSelectTemplate(scope.row.id)"
                         v-if="selectTemplateListQuery.type == '1'">选择模板
              </el-button>
              <el-button size="mini" type="warning" @click="handleDownloadTemplate(scope.row.id)"
                         v-if="selectTemplateListQuery.type == '0'">下载模板
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectTemplateDialogVisible = false" size="small">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="(currentSelectTemplate.remark)+' - 字段映射配置'"
               :visible.sync="fieldMapDialogVisible"
               width="80%">
      <div class="table-container">
        <el-table :data="fieldMapList"
                  style="width: 100%;"
                  :default-sort="{prop: 'sortNum', order: 'ascending'}"
                  v-loading="fieldMapLoading" border>
          <el-table-column label="字段名" align="center" prop="fieldName" disabled/>
          <el-table-column label="excel表头" align="center" prop="showName" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input type="textarea" autosize v-model="scope.row.showName"/>
            </template>
          </el-table-column>

          <el-table-column label="必填" align="center" prop="notNull" v-if="currentSelectTemplate.type == '0'">
            <template slot-scope="scope">
              <el-select v-model="scope.row.notNull" style="width:100%">
                <el-option label="必填" value="1"></el-option>
                <el-option label="非必填" value="0"></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="排序(越小越靠前)" align="center" prop="sortNum" sortable>
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.sortNum"/>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleDeleteOneFieldMap(scope.row.fieldName)">删除本行</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleSaveFieldMap" size="small" type="primary">保 存</el-button>
        <el-button @click="fieldMapDialogVisible = false" size="small">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  batchImportExportConfigDownload,
  batchImportExportConfigPostRequire,
  batchImportExportConfigPostRequireByConfig
} from '@/api/batchImportExportConfig'
import {batchImportExportFieldConfigPostRequire} from '@/api/batchImportExportFieldConfig'

const defaultListQuery = {
  current: 1,
  pageSize: 10,
  tableName: undefined,
  type: undefined,

}
const defaultProjectTableBatchImport = {
  id: undefined,
  tableName: undefined,
  remark: undefined,
  createTime: undefined,
  updateTime: undefined,
  type: undefined,

}

export default {
  name: 'projectTableBatchImportList',
  data() {
    return {
      listQuery: this.$deepClone( defaultListQuery),
      list: null,
      allTableNameToDesc: {},
      allTableNameToDescOption: [],
      total: null,
      listLoading: false,
      addDialogVisible: false,
      editDialogVisible: false,

      selectTemplateList: [],
      selectTemplateDialogVisible: false,
      selectTemplateListLoading: false,
      selectTemplateListQuery: {
        current: 1,
        pageSize: 10,
        tableName: "project_table_batch_import",
        type: undefined,
      },

      fieldMapList: [],
      fieldMapDialogVisible: false,
      fieldMapLoading: false,
      currentSelectTemplate: {},

      batchImportExportConfig: this.$deepClone( defaultProjectTableBatchImport)
    }
  },
  created() {
    this.getList()
    this.getAllTableInfo()
  },
  methods: {
    handleBatchImport() {
      this.selectTemplateListQuery.type = '0'
      this.selectTemplateListLoading = true
      this.selectTemplateDialogVisible = true
      this.selectTemplateList = []
      batchImportExportConfigPostRequire('listPage', this.selectTemplateListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateListLoading = false
        this.selectTemplateList = response.data.records
      })
    },
    handleBatchExport() {
      this.selectTemplateListQuery.type = '1'
      this.selectTemplateListLoading = true
      this.selectTemplateDialogVisible = true
      this.selectTemplateList = []
      batchImportExportConfigPostRequire('listPage', this.selectTemplateListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateListLoading = false
        this.selectTemplateList = response.data.records
      })
    },
    handleDownloadTemplate(configId) {
      batchImportExportConfigDownload("getImportExcel", {exportConfigId: configId}).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      })
    },
    handleSelectTemplate(configId) {
      // 0：导入  1：导出
      let thisListQuery = JSON.parse(JSON.stringify(this.listQuery));
      thisListQuery.exportConfigId = configId
      batchImportExportConfigDownload('batchExport', thisListQuery).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      })
    },
    beforeFileUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isExcel) {
        this.$message.error('上传文件只能是 xls/xlsx 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isExcel && isLt5M;
    },
    handleSelectTemplateUpload(file, importConfigId) {
      let params = new FormData()
      params.append("xlsFile", file.file);
      params.append("importConfigId", importConfigId);
      let headers = {
        'Content-Type': 'multipart/form-data; name="xlsFile"'
      }
      batchImportExportConfigPostRequireByConfig('batchImport', params, headers).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.selectTemplateDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },

    handleSaveFieldMap() {
      batchImportExportFieldConfigPostRequire('addList', {batchImportExportFieldConfigs: JSON.stringify(this.fieldMapList)}).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.fieldMapDialogVisible = false
      })
    },
    handleDeleteOneFieldMap(fieldName) {
      let fieldMapList = this.fieldMapList || [];
      let deleteIndex = -1
      for (let i = 0; i < fieldMapList.length; i++) {
        if (fieldMapList[i].fieldName == fieldName) {
          deleteIndex = i
          break;
        }
      }
      if (deleteIndex >= 0) {
        fieldMapList.splice(deleteIndex, 1)
      }
      this.fieldMapList = fieldMapList
    },
    handleFieldMap(row) {
      this.currentSelectTemplate = row
      this.fieldMapLoading = true
      this.fieldMapDialogVisible = true
      batchImportExportConfigPostRequire('getTableInfo', {
        tableName: row.tableName,
        configId: row.id
      }).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        let dataList = response.data.dataList || []
        if (dataList.length > 0) {
          this.fieldMapList = dataList
        } else {
          let fieldMapList = []
          let fieldInfoList = response.data.fieldInfoList || []

          for (let i = 0; i < fieldInfoList.length; i++) {
            let f = fieldInfoList[i]
            if (f.type==='img' || f.type==='file'){
              //暂时忽略图片类型
              continue
            }
            fieldMapList.push({
              configId: row.id,
              fieldName: f.javaName,
              showName: f.desc,
              notNull: "0",
              sortNum: i * 10,
            })
          }
          this.fieldMapList = fieldMapList
        }
        this.fieldMapLoading = false
      })
    },
    handleResetSearch() {
      this.listQuery = this.$deepClone( defaultListQuery)
    },
    handleSearchList() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.current = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    handleAdd() {
      this.addDialogVisible = true
      this.batchImportExportConfig = this.$deepClone( defaultProjectTableBatchImport)
    },
    handleAddDialogConfirm() {
      batchImportExportConfigPostRequire('add', this.batchImportExportConfig).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.addDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除该数据导入导出管理?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchImportExportConfigPostRequire('delete', {'id': row.id}).then(response => {
          if (response) {
            this.$message({
              type: response.status ? 'success' : 'error',
              message: response.message
            })
          }
        }).finally(() => {
          this.getList()
        })
      })
    },
    handleUpdate(row) {
      this.editDialogVisible = true
      this.batchImportExportConfig = this.$deepClone( row)
    },
    handleEditDialogConfirm() {
      batchImportExportConfigPostRequire('update', this.batchImportExportConfig).then(response => {
        if (response) {
          this.$message({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
        this.editDialogVisible = false
      }).finally(() => {
        this.getList()
      })
    },
    getList() {
      this.listLoading = true
      batchImportExportConfigPostRequire('listPage', this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.records
        this.total = response.data.total
      })
    },
    getAllTableInfo() {
      this.listLoading = true
      batchImportExportConfigPostRequire('getAllTableInfo').then(response => {
        this.listLoading = false
        let allTableNameToDesc = response.data || {}
        let allTableNameToDescOption = []
        let keys = Object.keys(allTableNameToDesc)
        for (let i = 0; i < keys.length; i++) {
          allTableNameToDescOption.push({
            label: allTableNameToDesc[keys[i]] + "-" + keys[i],
            value: keys[i]
          })
        }
        this.allTableNameToDescOption = allTableNameToDescOption
        this.allTableNameToDesc = allTableNameToDesc
      })
    }
  }
}
</script>
<style></style>
